package com.bosintek.wordtest.util;

import java.io.IOException;
import java.io.StringReader;
import java.util.Vector;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.bosintek.wordtest.Bank;
import com.bosintek.wordtest.WordSet;

public class XMLfunctions {

	public final static Document XMLfromString(String xml) {

		Document doc = null;

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {

			DocumentBuilder db = dbf.newDocumentBuilder();

			InputSource is = new InputSource();
			is.setCharacterStream(new StringReader(xml));
			doc = db.parse(is);

		} catch (ParserConfigurationException e) {
			System.out.println("XML parse error: " + e.getMessage());
			return null;
		} catch (SAXException e) {
			System.out.println("Wrong XML file structure: " + e.getMessage());
			return null;
		} catch (IOException e) {
			System.out.println("I/O exeption: " + e.getMessage());
			return null;
		}

		return doc;

	}

	/**
	 * Returns element value
	 * 
	 * @param elem
	 *            element (it is XML tag)
	 * @return Element value otherwise empty String
	 */
	public final static String getElementValue(Node elem) {
		Node kid;
		if (elem != null) {
			if (elem.hasChildNodes()) {
				for (kid = elem.getFirstChild(); kid != null; kid = kid
						.getNextSibling()) {
					if (kid.getNodeType() == Node.TEXT_NODE) {
						return kid.getNodeValue();
					}
				}
			}
		}
		return "";
	}

	public static int numResults(Document doc) {
		Node results = doc.getDocumentElement();
		int res = -1;

		try {
			res = Integer.valueOf(results.getAttributes().getNamedItem("count")
					.getNodeValue());
		} catch (Exception e) {
			res = -1;
		}
		return res;
	}

	public static String getValue(Element item, String str) {
		NodeList n = item.getElementsByTagName(str);
		return XMLfunctions.getElementValue(n.item(0));
	}

	public static int errorCode(Document doc) {
		int code;
		NodeList node = doc.getElementsByTagName("state");
		Element e = (Element) node.item(0);
		code = Integer.parseInt(e.getAttribute("code"));
		return code;
	}

	public static Vector<Bank> parseBanks(Document doc) {
		Vector<Bank> banks = new Vector<Bank>();
		if(doc==null){
			return banks;
		}
		Bank actualBank;
		actualBank = new Bank();

		NodeList bankNodes = doc.getElementsByTagName("bank");
		for (int ii = 0; ii < bankNodes.getLength(); ii++) {
			Element bankE = (Element) bankNodes.item(ii);
			actualBank.setID(bankE.getAttribute("id"));
			actualBank.setName(bankE.getAttribute("name"));			
			actualBank.setLang1(bankE.getAttribute("lang1"));
			actualBank.setLang2(bankE.getAttribute("lang2"));
			actualBank.setLevel(bankE.getAttribute("level"));
			actualBank.setTopic(bankE.getAttribute("topic"));
			actualBank.setTopic(bankE.getAttribute("timestamp"));
			NodeList nodes = bankE.getElementsByTagName("wset");
			
			for (int i = 0; i < nodes.getLength(); i++) {
				WordSet actualWSet = new WordSet();
				Element e = (Element) nodes.item(i);
				actualWSet.setMeaning(XMLfunctions.getValue(e, "meaning"));
				actualWSet.setWord(XMLfunctions.getValue(e, "word"));
				actualBank.addWSet(actualWSet);
			}
			banks.add(actualBank);
		}

		return banks;
	}
}
